package com.ztgf.commodity.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.common.config.YmlConfig;
import com.ztgf.commodity.mapper.CommodityAdvisoryPriceMapper;
import com.ztgf.commodity.models.bo.CommodityAdvisoryPriceSaveBO;
import com.ztgf.commodity.models.dto.BrandInfoDTO;
import com.ztgf.commodity.models.dto.CommodityAdvisoryPriceDTO;
import com.ztgf.commodity.models.service.IBrandInfoService;
import com.ztgf.commodity.models.service.ICommodityAdvisoryPriceService;
import com.ztgf.commodity.models.vo.*;
import com.ztgf.common.utils.StrUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import static com.ztgf.common.utils.UtilConstants.*;

/**
 * 询价表控制器
 *
 * @author chenyu.wang
 * @Date 2020-05-27 11:06:36
 */
@Slf4j
@DubboService
public class CommodityAdvisoryPriceServiceImpl extends ServiceImpl<CommodityAdvisoryPriceMapper, CommodityAdvisoryPriceDTO> implements ICommodityAdvisoryPriceService {

    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private IBrandInfoService iBrandInfoService;

    @Override
    public boolean add(CommodityAdvisoryPriceSaveBO saveBO) {
        CommodityAdvisoryPriceDTO dto = new CommodityAdvisoryPriceDTO();
        dto.setAreaId(saveBO.getAreaId());
        dto.setCategoryId(saveBO.getCategoryId());
        dto.setBrandId(saveBO.getBrandId());
        dto.setSpecificationAttributesIds(saveBO.getSpecificationAttributesIds());
        dto.setBudget(saveBO.getBudget());
        dto.setPayType(saveBO.getPayType());
        dto.setShopId(saveBO.getShopId());
        dto.setId(ymlConfig.getPkId());
        dto.setCreateUserId(saveBO.getShopId());
        dto.setReceiving(saveBO.getReceiving());
        return this.insert(dto);
    }

    @Override
    public List<CommodityAdvisoryPriceVO> queryInquiryResult(Long shopId, Integer sort) {
        List<CommodityAdvisoryPriceVO> realList = new ArrayList<>();
        CommodityAdvisoryPriceVO vo = baseMapper.queryInquiryResult(shopId);
        if (vo == null) {
            return null;
        }
        if (sort == ONE) {
            //价格由低到高
            List<CommodityAdvisoryGoodsVO> all = new ArrayList<>();
            List<CommodityAdvisoryGoodsVO> list = baseMapper.queryInquiryGoods(vo, sort);//查普通商品sku
            List<CommodityAdvisoryGoodsVO> comboGoods = baseMapper.queryComboGoods(vo, sort);//查套餐商品
            if (!isNull(list)) {
                vo.setCommodityInfo(list.get(ZERO).getCommodityName() + list.get(ZERO).getBrandName());
            }
            all.addAll(list);
            all.addAll(comboGoods);
            if (!isNull(all)) {
                vo.setGoods(all);
            }
            realList.add(vo);
            return realList;
        } else if (sort == TWO) {
            //同一店铺
            List<CommodityAdvisoryGoodsVO> shopList = baseMapper.queryInquiryGoods(vo, sort);//查店铺
            for (CommodityAdvisoryGoodsVO shop : shopList) {
                CommodityAdvisoryPriceVO commodityAdvisoryPriceVO = new CommodityAdvisoryPriceVO();
                BeanUtils.copyProperties(vo, commodityAdvisoryPriceVO);
                commodityAdvisoryPriceVO.setSellerShopId(shop.getShopId());
                //查店铺下商品
                List<CommodityAdvisoryGoodsVO> all = new ArrayList<>();
                List<CommodityAdvisoryGoodsVO> list = baseMapper.queryInquiryGoods(commodityAdvisoryPriceVO, 0);//查普通商品sku
                List<CommodityAdvisoryGoodsVO> comboGoods = baseMapper.queryComboGoods(commodityAdvisoryPriceVO, 0);//查套餐商品
                commodityAdvisoryPriceVO.setCommodityInfo(list.get(ZERO).getCommodityName() + list.get(ZERO).getBrandName());
                all.addAll(list);
                all.addAll(comboGoods);
                commodityAdvisoryPriceVO.setGoods(all);
                realList.add(commodityAdvisoryPriceVO);
            }
            return realList;
        } else {
            List<CommodityAdvisoryGoodsVO> list = baseMapper.queryInquiryGoods(vo, 0);//查普通商品sku
            List<CommodityAdvisoryGoodsVO> comboGoods = baseMapper.queryComboGoods(vo, 0);//查套餐商品
            List<CommodityAdvisoryGoodsVO> all = new ArrayList<>();
            if (!isNull(list)) {
                vo.setCommodityInfo(list.get(ZERO).getCommodityName() + list.get(ZERO).getBrandName());
            }
            all.addAll(list);
            all.addAll(comboGoods);
            if (!isNull(all)) {
                vo.setGoods(all);
            }
            realList.add(vo);
            return realList;
        }
    }

    @Override
    public List<CommodityAllFinallyCategoryVO> queryAllFinallyCategory() {
        return baseMapper.queryAllFinallyCategory();
    }

    @Override
    public List<BrandInfoDTO> queryAllBrand() {
        Wrapper<BrandInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("status", ZERO).eq("is_publish", ONE);
        return iBrandInfoService.selectList(wrapper);
    }

    @Override
    public List<SpecificationCategoryVO> getSpecificationCategory(Long categoryId, String condition) {
        return baseMapper.getSpecificationByCategory(categoryId, condition);
    }

    @Override
    public List<CommodityAdvisoryPriceVO> queryByFile(byte[] input) {
        List<CommodityAdvisoryExcelVO> list = new ArrayList<>();
        //将文件byte转成inputStream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(input);
        try {
            Workbook workbook = WorkbookFactory.create(inputStream);
            inputStream.close();
            //工作表对象
            Sheet sheet = workbook.getSheetAt(ZERO);
            //获取Excel表格中数据的行数
            int num = sheet.getPhysicalNumberOfRows();
            for (int i = TWO; i < num; i++) {
                // 取i第行
                Row row = sheet.getRow(i);
                //若有空行继续下一行（因为EXCEL有空行时报错故加上此代码）
                if (row == null || "".equals(row)) {
                    num--;
                    continue;
                }
                CommodityAdvisoryExcelVO vo = new CommodityAdvisoryExcelVO();
                vo.setProductName(this.getCellValue(row.getCell(ONE)));//产品名称
                vo.setSpecificationModel(this.getCellValue(row.getCell(TWO)));//规格型号
                vo.setBrand(this.getCellValue(row.getCell(THREE)));//品牌
                vo.setUnit(this.getCellValue(row.getCell(FOUR)));//单位
                String cellValue = this.getCellValue(row.getCell(FIVE));
                if(StrUtils.isEmpty(cellValue)){
                    vo.setAmount(0);//数量
                }else{
                    vo.setAmount(Integer.valueOf(this.getCellValue(row.getCell(FIVE))));//数量
                }
                vo.setDeliveryLocation(this.getCellValue(row.getCell(SEVEN)));//交付地点
                vo.setAdaptationShieldMachineBrand(this.getCellValue(row.getCell(EIGHT)));//适配盾构机品牌
                vo.setAdaptationSieldMachine(this.getCellValue(row.getCell(NINE)));//适配盾构机型号以及具体适用部位
                vo.setRemark(this.getCellValue(row.getCell(TEN)));//备注
                list.add(vo);
            }
            return this.queryRest(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /*
     * @description:获取excel数据时对数据类型的判定及处理
     * @author: chenyu.wang
     * @date: 2020-08-13
     * @param:
     * @return:
     */
    private String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                cellValue = cell.getStringCellValue().trim();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                DecimalFormat df = new DecimalFormat("0");

                cellValue = df.format(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA:
                cellValue = cell.getCellFormula();
                break;
            default:
                cellValue = "";
        }
        return cellValue;
    }


    /*
     * @description:excel查询结果
     * @author: chenyu.wang
     * @date: 2020-08-13
     * @param:
     * @return:
     */
    public List<CommodityAdvisoryPriceVO> queryRest(List<CommodityAdvisoryExcelVO> list) {
        if (list != null && list.size() > 0) {
            List<CommodityAdvisoryPriceVO> realList = new ArrayList<>();
            for (CommodityAdvisoryExcelVO excelVO : list) {
                //查询结果
                List<CommodityAdvisoryGoodsVO> goodsVOS = baseMapper.queryExcelAdvisoryPrice(excelVO);
                CommodityAdvisoryPriceVO priceVO = new CommodityAdvisoryPriceVO();
                priceVO.setBudgetPrice(new BigDecimal("0"));
                priceVO.setSendAreaName(excelVO.getDeliveryLocation());
                priceVO.setPayType(0);
                priceVO.setCommodityInfo(excelVO.getProductName() + excelVO.getSpecificationModel());
                priceVO.setGoods(goodsVOS);
                realList.add(priceVO);
            }
            return realList;
        }
        return null;
    }

}
